<?php

namespace App\Http\Controllers\App;

use App\Model\Cards;
use App\Model\UserDetail;
use App\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class RewardController extends Controller
{
    public function rank()
    {
        $page = User::select('id', 'rewards_all')->whereIn('type', [3, 4])->where('rewards_all', '>', 0)->orderByDesc('rewards_all')->orderBy('id')->paginate(request('limit', 18));
        $users = collect($page->items());
        $cards = Cards::select('user_id', 'user_name', 'head_picture')->whereIn('user_id', $users->pluck('id'))->get()->keyBy('user_id')->toArray();
        $details = UserDetail::select('user_id', 'wechat_name', 'head_portrait')->whereIn('user_id', $users->pluck('id'))->get()->keyBy('user_id')->toArray();
        $data = [];
        foreach ($users as $user) {
            $tmp = [];
            $tmp['user_id'] = $user->id;
            $tmp['reward'] = $user->rewards_all;
            $tmp['name'] = '';
            $tmp['avatar'] = '';
            if (isset($cards[$user->id])){
                if ($cards[$user->id]['user_name']) {
                    $tmp['name'] = $cards[$user->id]['user_name'];
                }
                if ($cards[$user->id]['head_picture']) {
                    $tmp['avatar'] = $cards[$user->id]['head_picture'];
                }
            }elseif (isset($details[$user->id])) {
                if ($details[$user->id]['wechat_name']) {
                    $tmp['name'] = $details[$user->id]['wechat_name'];
                }
                if ($details[$user->id]['head_portrait']) {
                    $tmp['avatar'] = $details[$user->id]['head_portrait'];
                }
            }
            $data[] = $tmp;
        }
        $page = $page->toArray();
        $page['data'] = $data;
        return $this->renderJson($page);
    }
}
